package com.pureut.storage.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pureut.storage.domain.MaterialFreezing;
import com.pureut.storage.domain.WmsStockInfo;
import com.pureut.storage.dto.MaterialFreezingDto;
import com.pureut.storage.dto.WmsStockInfoDto;
import com.pureut.storage.mapper.CustomerManagementMapper;
import com.pureut.storage.mapper.MaterialFreezingMapper;
import com.pureut.storage.mapper.OrderSupplierManagementMapper;
import com.pureut.storage.mapper.WmsStockInfoMapper;
import com.pureut.storage.service.MaterialFreezingService;
import com.pureut.storage.service.WmsStockInfoService;
import com.pureut.storage.vo.MaterialFreezingVo;
import com.pureut.storage.vo.WmsStockInfoVo;
import com.sale.common.core.constant.CacheNames;
import com.sale.common.core.exception.GlobalException;
import com.sale.common.core.utils.StringUtils;
import com.sale.common.core.utils.bean.BeanUtils;
import com.sale.common.dict.utils.DictUtils;
import com.sale.common.mybatis.core.page.PageQuery;
import com.sale.common.mybatis.core.page.TableDataInfo;
import com.sale.common.redis.utils.CacheUtils;
import com.sale.common.satoken.utils.LoginHelper;
import com.sale.system.api.RemoteUnitService;
import com.sale.system.api.domain.SysAuxiliary;
import com.sale.system.api.domain.SysDictData;
import com.sale.system.api.model.MaterialUnitDto;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author: CM
 * @date: 2023/1/6  18:19
 */
@Service
public class MaterialFreezingServiceImpl extends ServiceImpl<MaterialFreezingMapper, MaterialFreezing> implements MaterialFreezingService {

    @Resource
    private WmsStockInfoMapper wmsStockInfoMapper;

    @Resource
    private MaterialFreezingMapper materialFreezingMapper;

    @Resource
    private WmsStockInfoService wmsStockInfoService;

    @Resource
    private CustomerManagementMapper customerManagementMapper;

    @Resource
    private OrderSupplierManagementMapper orderSupplierManagementMapper;

    @DubboReference
    RemoteUnitService remoteUnitService;

    /**
     * 冻结查询仓库列表
     *
     * @param wmsStockInfoVo
     * @return
     */
    @Override
    public TableDataInfo<WmsStockInfoDto> getStockInfoList(WmsStockInfoVo wmsStockInfoVo,PageQuery pageQuery) {
        Page<WmsStockInfoDto> wmsStockInfoList = wmsStockInfoMapper.getWmsStockInfoList(wmsStockInfoVo, pageQuery.build());
        return TableDataInfo.build(wmsStockInfoList);
    }

    /**
     * 新增物料冻结单
     * @param materialFreezingVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addPickingComplete(MaterialFreezingVo materialFreezingVo) {
        List<WmsStockInfoVo> list = materialFreezingVo.getList();
        if (list.size() == 0) {
            throw new GlobalException("请至少选择一条单据");
        }
        List<MaterialFreezing> freezingList = new ArrayList<MaterialFreezing>();
        for (WmsStockInfoVo wmsStockInfoVo : list) {

            WmsStockInfo wmsStockInfo1 = wmsStockInfoMapper.selectOne(new QueryWrapper<WmsStockInfo>().lambda().eq(WmsStockInfo::getWsiMaterialNumber, wmsStockInfoVo.getWsiMaterialNumber()));

            MaterialFreezing materialFreezing = new MaterialFreezing();
            BeanUtils.copyProperties(materialFreezingVo, materialFreezing);
            materialFreezing.setMaterialNumber(wmsStockInfoVo.getWsiMaterialNumber());
            //设置单据状态为冻结
            materialFreezing.setMaterialStatus(1);
            if (StringUtils.isNotEmpty(wmsStockInfo1.getWsiMaterialGrade())){
                materialFreezing.setMaterialGrade(Integer.parseInt(wmsStockInfo1.getWsiMaterialGrade()));
            }

            //冻结原因
            materialFreezing.setFreezingCause(materialFreezingVo.getFreezingCause());
            materialFreezing.setFreezingUser(LoginHelper.getUsername());
            materialFreezing.setFreezingTime(new Date());

            materialFreezing.setDeptId(LoginHelper.getDeptId());

            freezingList.add(materialFreezing);

            //查询当前物料号码对应的单据
            WmsStockInfo wmsStockInfo = wmsStockInfoMapper.selectOne(new QueryWrapper<WmsStockInfo>().lambda().eq(WmsStockInfo::getWsiMaterialNumber, wmsStockInfoVo.getWsiMaterialNumber()));
            //修改仓库物料状态为冻结
            wmsStockInfo.setWsiFreezeInfo("1");
            wmsStockInfoMapper.updateById(wmsStockInfo);
        }
        return saveBatch(freezingList);
    }

    /**
     * 查看冻结列表
     *
     * @param materialFreezingVo
     * @return
     */
    @Override
    public TableDataInfo<MaterialFreezingDto> getList(MaterialFreezingVo materialFreezingVo, PageQuery pageQuery) {
        Page<MaterialFreezingDto> materialFreezingList = materialFreezingMapper.getMaterialFreezingList(materialFreezingVo,pageQuery.build());
        //单位集合
        Map<String, MaterialUnitDto> unitByCodeToMap = remoteUnitService.getUnitByCodeToMap();


        //获取其他入库状态字典值
        List<SysDictData> statusArray = DictUtils.getDictCache("freezing_status");
        Map<String, String> freezingStatusMap = statusArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        List<SysDictData> gradeArray = DictUtils.getDictCache("freezing_grade");
        Map<String, String> gradeMap = gradeArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        List<MaterialFreezingDto> records = materialFreezingList.getRecords();
        for (MaterialFreezingDto materialFreezingDto : records) {
            //单位
            if(materialFreezingDto.getMaterialUnit() != null){
                materialFreezingDto.setMaterialUnitDict(unitByCodeToMap.get(materialFreezingDto.getMaterialUnit()).getUnitName());
            }
            //辅助属性
            List<SysAuxiliary> statsArray = CacheUtils.get(CacheNames.SYS_GINSENG + "_" + materialFreezingDto.getTenantId(), String.valueOf(materialFreezingDto.getMaterialId()));
            materialFreezingDto.setAuxiliaryAttribute(statsArray);

            String materialStatus = materialFreezingDto.getMaterialStatus();
            String materialGrade = materialFreezingDto.getMaterialGrade();
            materialFreezingDto.setMaterialStatusDict(materialStatus);
            materialFreezingDto.setMaterialStatus(freezingStatusMap.get(materialStatus));

            materialFreezingDto.setMaterialGrade(materialGrade);
            materialFreezingDto.setMaterialGradeDict(gradeMap.get(materialGrade));
        }
        return TableDataInfo.build(materialFreezingList);
    }

    /**
     * 解冻
     * @param materialFreezingVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateFreezing(MaterialFreezingVo materialFreezingVo) {
        List<WmsStockInfoVo> list = materialFreezingVo.getList();
        List<Long> idStr = new ArrayList<>();
        for (WmsStockInfoVo wmsStockInfoVo : list) {
            Long ids = wmsStockInfoVo.getIds();
            idStr.add(ids);
        }

        if (idStr.size() < 1) {
            throw new GlobalException("至少勾选一条数据");
        }
        List<MaterialFreezing> freezingList = new ArrayList<>();

        //物料号码列表
        List<String> materialNumberList = new ArrayList<>();

        List<MaterialFreezing> materialFreezings = materialFreezingMapper.selectList(new QueryWrapper<MaterialFreezing>().lambda().in(MaterialFreezing::getId, idStr));
        for (MaterialFreezing entity : materialFreezings) {

            materialNumberList.add(entity.getMaterialNumber());

            if (entity.getMaterialStatus() == 1) {
                entity.setMaterialStatus(2);
                entity.setMaterialGrade(1);
                //解冻原因
                entity.setThawCause(materialFreezingVo.getThawCause());
                entity.setThawUser(LoginHelper.getUsername());
                entity.setThawTime(new Date());
                freezingList.add(entity);
            } else {
                throw new GlobalException("只能对冻结状态的物料进行解冻操作");
            }
        }
        boolean b = updateBatchById(freezingList);
        //修改仓库数据状态
        List<WmsStockInfo> wmsStockInfoList = new ArrayList<>();
        List<WmsStockInfo> wmsStockInfo = wmsStockInfoMapper.selectList(new QueryWrapper<WmsStockInfo>().lambda().in(WmsStockInfo::getWsiMaterialNumber, materialNumberList));
        for (WmsStockInfo entity : wmsStockInfo) {
            entity.setWsiFreezeInfo("2");
            entity.setWsiMaterialGrade("1");
            wmsStockInfoList.add(entity);
        }
        if (b) {
            return wmsStockInfoMapper.updateBatchById(wmsStockInfoList);
        }
        return b;
    }

    /**
     * 品质处理
     *
     * @param materialFreezingVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateGradeFreezing(MaterialFreezingVo materialFreezingVo) {

        List<WmsStockInfoVo> list = materialFreezingVo.getList();
        if (list.size() == 0) {
            throw new GlobalException("至少勾选一条数据");
        }
        List<MaterialFreezing> freezingList = new ArrayList<>();
        List<WmsStockInfo> wmsStockInfoList = new ArrayList<>();
        for (WmsStockInfoVo wmsStockInfoVo : list) {
            long id = wmsStockInfoVo.getIds();
            MaterialFreezing materialFreezing = materialFreezingMapper.selectById(id);
            int materialStatus = materialFreezing.getMaterialStatus();
            materialFreezing.setMaterialGrade(materialFreezingVo.getMaterialGrade());
            materialFreezing.setMaterialStatus(2);
            freezingList.add(materialFreezing);
            if (materialStatus != 1) {
                throw new GlobalException("只能对冻结状态的物料进行品质处理操作");
            }
            WmsStockInfo wmsStockInfo = wmsStockInfoMapper.selectOne(new QueryWrapper<WmsStockInfo>().lambda().eq(WmsStockInfo::getWsiMaterialNumber, materialFreezing.getMaterialNumber()));
            wmsStockInfo.setWsiFreezeInfo("2");
            wmsStockInfo.setWsiMaterialGrade(String.valueOf(materialFreezingVo.getMaterialGrade()));
            wmsStockInfoList.add(wmsStockInfo);
        }

        //修改物料冻结状态为解冻
        boolean free = updateBatchById(freezingList);
        //关闭仓库物料冻结信息标识

        if (free) {
            return wmsStockInfoMapper.updateBatchById(wmsStockInfoList);
        } else {
            throw new GlobalException("品质处理失败");
        }
    }

    /**
     * 回显单据
     *
     * @param ids
     * @return
     */
    @Override
    public List<MaterialFreezingDto> view(String ids) {
        //将ids根据逗号拆分成数组
        List<String> idStr = Arrays.asList(ids.split(","));
        if (idStr.size() == 0) {
            throw new GlobalException("请至少勾选一条单据");
        }
        String[] split = ids.split(",");
        List<String> list = Arrays.asList(split);
        //根据ids批量查询出list列表
        List<MaterialFreezingDto> materialFreezingList = materialFreezingMapper.selectFreeIds(list);

        //List<MaterialFreezingDto> list = new ArrayList<>();


            //list.add(materialFreezingDto);


        return materialFreezingList;
    }


}
